let courseName_const = localStorage.getItem("courseName");

function getUrlParam(name) {
    //构造一个含有目标参数的正则表达式对象
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //匹配目标参数
    let r = window.location.search.substr(1).match(reg);
    //返回参数
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
}




//
//     new_element=document.createElement("script");
//     new_element.setAttribute("type","text/javascript");
//     new_element.setAttribute("src","diy-autoHeight.js");// 在这里引入了a.js
//     document.body.appendChild(new_element);
let course_content_num = [];//定义教学内容序号的空数组
let courseId = getUrlParam("courseId");
let course_content_Arr = []; // 定义教学内容空数组
let teacher_way_Arr = []; //定义教学方式空数组
let l_out_Arr = [] //定义课程目标空数组
let content_length = 0;
let index;//元素索引值
let course_target = [];
let userId_const = localStorage.getItem("userId");

let userName_const = localStorage.getItem("userName");
let current_courseName;
let username = $(".dropdown-user-name");
username.find('i').remove();
let user_name = '<i>你好，'+userName_const+'老师</i>';
username.append(user_name);                       //生成导航栏的老师名字
username = $("#user_name");
username.find('span').remove();
user_name = '<span>'+userName_const+'老师</span>'      //生成导航栏下拉框的老师名字
username.append(user_name);
//多个文本框数据合并传入数据库

function Total() {
    course_content_Arr = []; //用来记录课程内容文本框中的文本
    teacher_way_Arr = [];    //用来记录教学方式文本框中的文本
    l_out_Arr = [];          //用来记录学习产出文本框中的文本
    let txt1 = $("#course_content_text").find('textarea'); // 获取所有文本框
    let txt2 = $("#lOut_text").find('textarea');
    let txt3 = $("#teacher_way_text").find('textarea');
    for (let i = 0; i<txt1.length; i++) {
        course_content_Arr.push(txt1.eq(i).val()); // 将文本框的值添加到数组中
    }
    for (let i = 0; i<txt2.length; i++){
        l_out_Arr.push(txt2.eq(i).val());
    }
    for (let i = 0; i<txt3.length; i++){
        teacher_way_Arr.push(txt3.eq(i).val());
    }

}

//自动获取课程名
function getName(){
    $.ajax({
        url: '/msg/findByCourseId_C',
        type: 'get',
        dataType: 'json',
        async: false,
        data: {"userId": userId_const, "courseId": courseId},
        success:function (data){
            current_courseName=data[0].courseName;
            localStorage.setItem('courseName',current_courseName);
            let a=localStorage.getItem('courseName');
            console.log("a");
            console.log(a);

        }
    })
}
function auTotHeight(){
    autosize(document.querySelectorAll('textarea'));
}
//textarea自动高度
// function auTotHeight () {
//     function DiyArea (el) {
//         this.el = el || {}
//         // let height =document.querySelectorAll("textarea");
//         this.config = {
//             el: document.querySelectorAll('textarea')
//         }
//         this.init()
//     }
//
//     DiyArea.prototype = {
//         init: function () {
//             this.bindEvent()
//         },
//         bindEvent: function () {
//             if (!this.config.el) {
//                 return false
//             }
//             if (this.config.el[0].addEventListener) {
//                 for (var i = 0; i < this.config.el.length; i++) {
//                     if (this.config.el[i].getAttribute('data-allow') === 'no-allow') {
//                         continue
//                     }
//                     this.config.el[i].addEventListener('input', function (e) {
//                         console.log(this.style.height)
//                         this.style.height = 'auto'
//                         this.style.height = this.scrollHeight + 'px'
//                     })
//                 }
//             }
//         }
//     }
//     return new DiyArea('diy-area')
// }
function All_submit(){
    let own_target_i = [];
    let part = new RegExp("[1-9]");
    let trContent = "";


    $("#course-content tr").each(function (){
        $(this).children("td").each(function () {
            let checkbox = $(this).find(':checkbox:checked');

            if(checkbox.length > 0) {
                checkbox.each(function (i) {
                    //各个课程目标教学环节
                    let own_target = $(checkbox[i]).val();
                    // console.log("own_target"+own_target);
                    trContent = trContent + own_target + "&";
                    // console.log("trContent"+trContent);
                });

            }
        });
        trContent = trContent.substring(0, trContent.length - 1);
        trContent = trContent + ";";

    });
    trContent = trContent.split(";");

    for(let i = 0 ;i< trContent.length-1;i++){

        let tdContent = trContent[i].split("&");
        for(let j in tdContent){
                if(own_target_i[i]!=null) {
                    own_target_i[i] += "课程目标" + part.exec(tdContent[j]) + ",";
                }else {
                    own_target_i[i] = "课程目标" + part.exec(tdContent[j]) + ",";
                }

        }
        console.log("own_target_i["+i+"]"+own_target_i[i])
    }
    $.ajax({
        url: '/msg/findById_content',
        type: 'get',
        dataType: 'json',
        async: false,
        data:{"courseId":courseId},
        success: function (data) {
            for(let i in data) {
                course_content_num[i] = data[i].contentId;
                console.log(course_content_num[i]);
            }
        }
    });
    for(let i = 1 ;i< trContent.length;i++) {
        console.log(i-1+"?"+own_target_i[i-1]);
        $.ajax({
            url: '/msg/updateOwnTarget',
            type: 'post',
            dataType: 'json',
            data: {"contentId": course_content_num[i], "ownTarget": own_target_i[i-1]}
        });
    }
    swal({title:"提交成功",type:"success"});
}


$(function (){
    let content=$(".content");//
    let lout=$(".lout");
    let teacherway=$(".teacherway")
    //删除某个教学环节
    content.on("click","span",function (){
        $.ajax({
            url: '/msg/findById_content',
            type: 'get',
            dataType: 'json',
            async: false,
            data:{"courseId":courseId},
            success: function (data) {
                for(let i in data) {
                    course_content_num[i] = data[i].contentId;

                }
            }
        });
        index = parseInt($(this).index()/2);// 删除按钮索引值
        console.log(index);
        content.find("textarea").eq(index).remove();
        content.find("span").eq(index).remove();
        $.ajax({
            url:'/msg/delete_content',
            type:'post',
            dataType:'json',
            data: {"contentId":course_content_num[index]},
            success: function(){
                findById();
            }
        });
    });
    //删除某个评价方式
    lout.on("click","span",function (){
        index = parseInt($(this).index()/2);// 删除按钮索引值
        console.log(index);
        lout.find("textarea").eq(index).remove();
        lout.find("span").eq(index).remove();
    });
    teacherway.on("click","span",function (){
        index = parseInt($(this).index()/2);// 删除按钮索引值
        console.log(index);
        teacherway.find("textarea").eq(index).remove();
        teacherway.find("span").eq(index).remove();
    });
})


$(function(){
    $("#add1").on('click',function(){
        let addContent='<textarea  name="textarea1" class="textarea " placeholder="教学内容" required="required">  </textarea><span> 删除 </span>'
        $(".content").append(addContent);
        content_length++;
        console.log("courseId"+courseId);
        $.ajax({
            url:'/msg/insert_content',
            type:'post',
            dataType:'json',
            data: {"courseId":courseId}
        });
    })
    $("#add2").on('click',function(){
        let add='<textarea  name="textarea2" class="textarea " placeholder="学习产出/学习目标" required="required"> </textarea><span> 删除 </span>'
        $(".lout").append(add);
    })
    $("#add3").on('click',function(){
        let add='<textarea name="textarea3"  class="textarea " placeholder="教学方式可能包括：课前自学，课堂讲授，讨论，实验等" required="required">  </textarea><span> 删除 </span>'
        $(".teacherway").append(add);
    })
});

//显示表格数据
function findById() {
    let course_content_keywords_input='';  //添加文本框
    let l_out_keywords_input='';
    let teacher_way_keywords_input='';
    $.ajax({
        url:'/msg/findByCourseId',
        type:'get',
        dataType:'json',
        data:{"courseId":courseId},
        success:function (data) {
            for(let i in data){
                course_target[i]=data[i].courseTargetContent;
                // console.log(course_target[i]);
            }

        }
    });
    console.log("courseId"+courseId);
    $.ajax({

        url: '/msg/findById_content',
        type: 'get',
        dataType: 'json',
        data:{"courseId":courseId},
        success: function (data) {
            //获取课程名
            let name=$("#courseName");
            name.empty();

            name.append(current_courseName);

            let teacher_key=[];//教学内容
            let lout_key=[];//学习产出/学习目标
            let teacher_way=[];//教学方式
            for(let i in data){
                if(null!=data[i].courseContent&&" "!=data[i].lOut){
                }else{
                    data[i].courseContent="还未填写具体内容！";
                }
                if(null!=data[i].lOut&&" "!=data[i].lOut){
                }else{
                    data[i].lOut="还未填写具体内容！";
                }
                if(null!=data[i].teacheWay&&" "!=data[i].lOut){
                }else{
                    data[i].teacheWay="还未填写具体内容！";
                }
                teacher_key[i]=data[i].courseContent;
                lout_key[i]=data[i].lOut;
                teacher_way[i]=data[i].teacheWay;
            }
            content_length=teacher_key.length;

            for(let i in teacher_key){
                course_content_keywords_input+='<textarea  class="textarea" ' + ' required="required"> '+
                    teacher_key[i] +'</textarea>  <span> 删除 </span>'
            }
            for(let i in lout_key){
                l_out_keywords_input+='<textarea  class="textarea" '+'title="'+lout_key[i]+'"' + ' required="required"> '+
                    lout_key[i] +' </textarea>   <span> 删除 </span>'
            }
            for(let i in teacher_way){
                teacher_way_keywords_input+='<textarea  class="textarea" '  + ' required="required"> '+
                    teacher_way[i] +'</textarea> <span> 删除 </span>'
            }

            if(teacher_key){
                let course_content_text=$("#course_content_text");
                course_content_text.find('textarea,span').remove();
                course_content_text.append(course_content_keywords_input);
            }
            if(lout_key){
                let lOut_text = $("#lOut_text");
                lOut_text.find('textarea,span').remove();
                lOut_text.append(l_out_keywords_input);
            }
            if(teacher_way){
                let teacher_way_text = $("#teacher_way_text");
                teacher_way_text.find('textarea,span').remove();
                teacher_way_text.append(teacher_way_keywords_input);

            }
            auTotHeight();

            let course_target_check = '';

            for (let i in  course_target) {
                course_target_check += '<label><input type="checkbox" value="' + course_target[i] + '"/>' + course_target[i] + '</label><br>';

            }
            //查询课程目标内容
            $.ajax({
                url:'/msg/findById_content',
                type:'get',
                dataType:'json',
                data:{"courseId":courseId},
                success:function (data) {
                    let course_content=$("#course-content");
                    course_content.find('tr').remove();
                    let auto = 1;
                    for (let i in data) {
                        console.log(data[i].lOut);

                        if(null!=data[i].courseContent&&" "!=data[i].lOut){
                        }else{
                            data[i].courseContent="还未填写具体内容！";
                        }
                        if(null!=data[i].lOut&&" "!=data[i].lOut){
                        }else{
                            data[i].lOut="还未填写具体内容！";
                        }
                        if(null!=data[i].teacheWay&&" "!=data[i].lOut){
                        }else{
                            data[i].teacheWay="还未填写具体内容！";
                        }
                        let tr;

                        // tr='<th scope="row"> '+auto +' </th>'
                        //     +'<td class="th_700">'+data[i].courseContent+'</td>'
                        //     +'<td class="th_600">'+data[i].lOut+'</td>'
                        //     +'<td class="th_400">'+data[i].teacheWay+'</td>'
                        //     +'<td class="th_400">'+course_target_check+'</td>'
                        tr='<th scope="row"> '+auto +' </th>'
                            +'<td class="th_700">'+data[i].courseContent+'</td>'
                            +'<td class="th_700">'+data[i].lOut+'</td>'
                            +'<td class="th_600">'+data[i].teacheWay+'</td>'
                            +'<td class="th_400">'+course_target_check+'</td>'
                        course_content.append('<tr>'+tr+'</tr>')
                        auto++;
                    }
                }
            });

        }

    });

}

$(document).ready(function() {
    getName();


    findById();
    Total();
    $(function () {
        $("#flip1").click(function () {
            $("#retract1").slideToggle("slow");
            console.log("收起");
        });
    });
    $(function () {
        $("#flip2").click(function () {
            $("#retract2").slideToggle("slow");
            console.log("收起");
        });
    });
    $(function () {
        $("#flip3").click(function () {
            $("#retract3").slideToggle("slow");
            console.log("收起");
        });
    });
    $(function () {
        $("#flip4").click(function () {
            $("#retract4").slideToggle("slow");
            console.log("收起");
        });
    });
    $(function (){
        $("#submit1").click(function (){

            $.ajax({
                url: '/msg/findById_content',
                type: 'get',
                dataType: 'json',
                async: false,
                data:{"courseId":courseId},
                success: function (data) {
                    for(let i in data) {
                        course_content_num[i] = data[i].contentId;
                        console.log(course_content_num[i]);
                    }
                }
            });
            let run=false;
            let index=0;
            Total();
            for(let i in course_content_Arr){
                if(!course_content_Arr[i].match(/^[ ]*$/))
                {
                    index++;
                }
                if(index===course_content_Arr.length)
                    run=true;
            }
            if(run===false){
                alert("输入框不能为空");
            }
            else{
                for(let i in course_content_num){
                    $.ajax({
                        url: '/msg/updateContent',
                        type: 'post',
                        dataType: 'json',
                        data:{"contentId":course_content_num[i],"courseContent":course_content_Arr[i].toString()},
                        success: function () {
                            findById();
                        }
                    });
                }
            }
        });
        $("#submit2").click(function (){
            $.ajax({
                url: '/msg/findById_content',
                type: 'get',
                dataType: 'json',
                async: false,
                data:{"courseId":courseId},
                success: function (data) {
                    for(let i in data) {
                        course_content_num[i] = data[i].contentId;
                        console.log(course_content_num[i]);
                    }
                }
            });
            run=false;
            index=0;
            Total();
            for(let i in l_out_Arr){
                if(!l_out_Arr[i].match(/^[ ]*$/)) {
                    index++;

                }
                if(index===l_out_Arr.length)
                    run=true;
            }

            if(run===false)
                alert("输入框不能为空");
            else {
                for (let i in course_content_num) {
                    $.ajax({
                        url: '/msg/updateLout',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            "contentId": course_content_num[i],
                            "lOut": l_out_Arr[i].toString()
                        },
                        success: function () {
                            findById();
                        }
                    });
                }
            }
        });
        $("#submit3").click(function (){
            $.ajax({
                url: '/msg/findById_content',
                type: 'get',
                dataType: 'json',
                async: false,
                data:{"courseId":courseId},
                success: function (data) {
                    for(let i in data) {
                        course_content_num[i] = data[i].contentId;
                        console.log(course_content_num[i]);
                    }
                }
            });
            run=false;
            index=0;
            Total();
            for(let i in teacher_way_Arr){
                if(!teacher_way_Arr[i].match(/^[ ]*$/)) {
                    index++;
                }
                if(index===teacher_way_Arr.length)
                    run=true;
            }

            if(run===false)
                alert("输入框不能为空");
            else {
                for (let i in course_content_num) {
                    $.ajax({
                        url: '/msg/updateTeacherWay',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            "contentId": course_content_num[i],
                            "teacheWay": teacher_way_Arr[i].toString()
                        },
                        success: function () {
                            findById();
                        }
                    });
                }
            }
        });

    })




})

